<?php
class LoginAction extends CommonAction {
	private $User;
	private $Email;
	private $ChongZhi;
	private $Type;
	private $Wallet;
	private $Ext;
	private $ExtLog;
	private $ChongZhiLog;
	private $Issue;
	private $Buy;
	public function __construct(){
        parent::__construct();
        $this->User=D('User');
		$this->Email=D('Email');
		$this->ChongZhi=D('ChongZhi');
		$this->Type=D('Type');
		$this->Wallet=D('Wallet');
		$this->Ext=D('Ext');
		$this->ExtLog=D('ExtLog');
		$this->assign('onpage','4');
		$this->ChongZhiLog=D('ChongZhiLog');
		$this->Issue=D('Issue');
		$this->Buy=D('Buy');
	}
	public function index(){
        $this->display('./Tpl/Home/login.html');
	}

	public function go(){
	    $username = $_POST['username'];
		$password = md5($_POST['password']);
        $user = $this->User->where('username=\''.$username.'\'')->find();
		$code = strtolower($_POST['code']);
		$checkcode = strtolower($_SESSION['checkcode']);

        if($code == $checkcode){
			
				if($user){

                    $a = strtotime($user['addtime']);
					$b = time();
					$d = intval(($b - $a)/(3600*24));
					if($user['isclose']==0){
						if($d >= $this->sysv['wait']){
						    $this->User->where('id='.$user['id'])->delete();
							$this->ChongZhi->where('userid='.$user['id'])->delete();
							$this->Wallet->where('userid='.$user['id'])->delete();
						}
						$this->error('对不起，您的帐号未激活，请登录注册邮箱激活帐号。');
						exit;
					}

                   $iscz = $this->ChongZhiLog->where('userid='.$user['id'])->count();
				   if($d >= $this->sysv['wait'] && !$iscz){
					   $this->User->where('id='.$user['id'])->delete();
					   $this->ChongZhi->where('userid='.$user['id'])->delete();
					   $this->Wallet->where('userid='.$user['id'])->delete();

					   $this->error('该账户不存在！');
					   exit;
				   }

 
                    $rmb = $this->ChongZhi->where('userid='.$user['id'].' and yuan=1')->find();
					$cfb = $this->ChongZhi->where('userid='.$user['id'].' and main=1')->find();
                    $buy = $this->Buy->where('userid='.$user['id'])->select();
					foreach($buy as $k => $v){
					    $issue = $this->Issue->where('id='.$v['issueid'])->find();
						if($issue['status']==1){
							$r['id'] = $rmb['id'];
						    $r['goldnum'] = coin($rmb['goldnum']+$v['nownum']*$v['price']);
							$this->ChongZhi->save($r);

							$c['id'] = $cfb['id'];
						    $c['goldnum'] = coin($cfb['goldnum']+$v['nownum']);
							$this->ChongZhi->save($c);
						}
					}

					if($user['password']==$password){
						$_SESSION['USER_KEY']=$username;
						$_SESSION['USER_KEY_ID']=$user['id'];

						$data['id']=$user['id'];
						$data['logintime']=date('Y-m-d H:i:s',time());
						$data['loginip']=get_client_ip();
						$this->User->save($data);

						$ext = $this->Ext->where('parentid='.$user['id'])->find();
						if($ext){
							$nowlen = time() - strtotime($ext['lasttime']);
							$reallen = strtotime($ext['lasttime']) + $ext['daynum'] * 24 * 3600;
							if($ext['nowcoin']>0 && $nowlen >= $reallen){
								$d['id'] = $ext['id'];
								$d['nowcoin'] = $ext['nowcoin']<$ext['percoin']?0:$ext['nowcoin'] - $ext['percoin'];
								$d['lasttime'] = date('Y-m-d H:i:s',strtotime($ext['lasttime'])+10*24*3600);
								$this->Ext->save($d);

								$cz = $this->ChongZhi->join('t_type t on t.main=1 and t_chong_zhi.typeid=t.id')->where('t_chong_zhi.userid='.$_SESSION['USER_KEY_ID'])->find();
								$czd['id'] = $cz['id'];
                                $per =  $ext['nowcoin']<$ext['percoin']?$ext['nowcoin']:$ext['percoin'];
								$czd['goldnum'] = coin($cz['goldnum'] + $per);
                                $this->ChongZhi->save($czd);
                            
								$dl['nowcoin'] = $d['nowcoin'];
								$dl['lasttime'] = $d['lasttime'];
								$dl['coin'] = $ext['coin'];
								$dl['percoin'] = $ext['percoin'];
								$dl['parentid'] = $ext['parentid'];
								$dl['sunid'] = $ext['sunid'];
								$dl['addtime'] = $ext['addtime'];
								$this->ExtLog->add($dl);
							}
						}

                        redirect($this->path.'/User');
					}else{
						$this->assign('jumpUrl',$this->path.'/Login');
						$this->error('帐号或密码错误！');
					}
				}else{
					$this->assign('jumpUrl',$this->path.'/Login');
					$this->error('该账户不存在！');
				}
			
		}else{
		    //$this->assign('jumpUrl','/Login');
			$this->error('验证码错误！');
		}
	}

	public function loginout(){
	    session(null);
		redirect($this->path.'/Login');
	}

	public function checkcode(){
	    $img_height=93;//先定义图片的长、宽  
		$img_width=32;  
		$authnum='';  
		//生产验证码字符  
		$ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";  
		$list=explode(",",$ychar);  
		for($i=0;$i<4;$i++){  
			$randnum=rand(0,35);  
			$authnum.=$list[$randnum];  
		}  
		//把验证码字符保存到session  
		$_SESSION["checkcode"] = $authnum;  
		  
		  
		$aimg = imagecreate($img_height,$img_width);    //生成图片  
		imagecolorallocate($aimg, 255,255,255);            //图片底色，ImageColorAllocate第1次定义颜色PHP就认为是底色了  
		$black = imagecolorallocate($aimg, 0,0,0);        //定义需要的黑色  
		  
		  
		for ($i=1; $i<=100; $i++) {  
			imagestring($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"@",imagecolorallocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));  
		}  
		  
		//为了区别于背景，这里的颜色不超过200，上面的不小于200  
		for ($i=0;$i<strlen($authnum);$i++){  
			imagestring($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(2,7),mt_rand(1,$img_width/2-2), $authnum[$i],imagecolorallocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));  
		}  
		imagerectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//画一个矩形  
		Header("Content-type: image/PNG");  
		ImagePNG($aimg);                    //生成png格式  
		ImageDestroy($aimg);
	}

	public function reg(){
		if(chkStr($_GET['invit'])){
		    $user = $this->User->where('inviturl=\''.$_GET['invit'].'\'')->find();
			if($user) $_SESSION['invit'] = $_GET['invit'];
		}
		$this->display('./Tpl/Home/reg.html');
    }

	public function insert(){

//		$code = strtolower($_POST['code']);
//		$checkcode = strtolower($_SESSION['checkcode']);

        if($code != $checkcode){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
		    $this->error('验证码错误！');
			exit(0);
		}
		
		$username   = trim($_POST['username']);
		$password   = trim($_POST['password']);
		$repassword = trim($_POST['repassword']);
		$email      = trim($_POST['email']);
		$alipay     = trim($_POST['alipay']);

		if(empty($username) || empty($password) || empty($repassword) || empty($email) || empty($alipay)){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('提交的信息不完整！');
			exit(0);
		}

        if(strlen($password)<6 || strlen($password)>20){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('密码不合法');
			exit(0);
		}

		if($password != $repassword){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('两次输入的密码不同！');
			exit(0);
		}

		if(!is_email($email)){
		    $this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('邮箱格式有误！');
			exit(0);
		}

		$user = $this->User->where('username=\''.$username.'\'')->find();
		if($user){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('该帐号已被使用！');
			exit(0);
		}

		$user = $this->User->where('email=\''.$email.'\'')->find();
		if($user){
			$this->assign('jumpUrl',$this->path.'/Login/reg/');
			$this->error('该邮箱地址已被使用！');
			exit(0);
		}

		$data['username'] = $username;
		$data['password'] = md5($password);
		$data['pwdshow']  = $password;
		$data['email']    = $email;
		$data['alipay']    = $alipay;
		$data['addtime']  = date('Y-m-d H:i:s',time());
		$data['hash'] = md5($data['username']+$data['password']+$data['email']+$data['addtime']);
		$data['inviturl'] = date('H',time()).rand(1000,9999);

		if(chkStr($_SESSION['invit'])){
			$data['invit'] = $_SESSION['invit'];
			$data['invit'] = $_SESSION['invit'];
		}
		
		$mo = new Model();
		$mo->startTrans();

		$isadd = $mo->table('t_user')->add($data);

        if($isadd){
			$e = $this->Email->where('id=1')->find();
			$url = $_SERVER['HTTP_HOST'].$this->path.'/Login/activate/uid/'.$isadd.'/hash/'.$data['hash'];
			$e['content'] = str_replace('[url]',$url,$e['content']);
			$issend = $this->sendEmail($data['email'],$e['title'],$e['content']);

			if(chkStr($_SESSION['invit'])){
				$u = $this->User->where('inviturl="'.$data['invit'].'"')->find();
				$ext['parentid'] = $u['id'];
				$ext['sunid'] = $isadd;
				$ext['coin'] = coin($this->sysv['extcoin']);
				$ext['percoin'] = coin($ext['coin'] * $this->sysv['extper'] / 100);
				$ext['nowcoin'] = coin($this->sysv['extcoin']);
				$ext['daynum'] = coin($this->sysv['exttime']);
				$ext['addtime'] = $data['addtime'];
				$rs = $this->Ext->add($ext);
			}else{
			    $rs = true;
			}
		}

        $cz = $this->ChongZhi->where('userid='.$isadd)->find();
		if($cz){
		    $isczurl = true;
		}else{
			$tb = $this->Type->select();
			foreach($tb as $k => $v){
			    $ds[$k]['typeid']=$v['id'];
				$ds[$k]['userid']=$isadd;
				//$ds[$k]['url']=$this->getArr($tb['url'],$tb['port'],$tb['username'],$tb['password'],$username);
			}

		    $isczurl = $mo->table('t_chong_zhi')->addAll($ds);
		}

		$wallet = $this->Wallet->where('userid='.$isadd)->find();
		if($wallet){
		    $iswallet = true;
		}else{
			$tb = $this->Type->select();
			foreach($tb as $k => $v){
			    $ws[$k]['typeid']=$v['id'];
				$ws[$k]['userid']=$isadd;
			}

		    $iswallet = $mo->table('t_wallet')->addAll($ws);
		}


		//if($isadd && $issend && $isczurl && $iswallet && $rs){
			$mo->commit();
			$this->assign('jumpUrl',$this->path.'/Login');
			$this->success('注册成功！请登录注册邮箱激活帐号。');
		//}else{
		//	$mo->rollback();
		//	$this->assign('jumpUrl',$this->path.'/Login/reg/');
		//	$this->error('注册失败！');
		//}
    }

	public function activate(){
	    if(empty($_GET['uid']) || empty($_GET['hash'])){
		    $this->error('激活失败!');
		}

		$user = $this->User->where('id='.$_GET['uid'].' and hash="'.$_GET['hash'].'"')->find();
		if($user){
			$data['isclose'] = 1;
            $data['hash'] = '';
		    if($this->User->where('id='.$user['id'])->save($data)){
			    $this->assign('jumpUrl',$this->path.'/Login');
				$this->success('激活成功！请登录。');
			}else{
				$this->error('激活失败!');
			}
		}else{
		    $this->error('激活失败!');
		}
	}

	public function checkusername(){
	    $username = trim($_POST['username']);
		if(!empty($username)){
		    $user = $this->User->where('username=\''.$username.'\'')->find();
			if($user){
			    echo 1;
			}else{
			    echo 2;
			}
		}else{
		    echo 0;
		}
	}

	public function checkemail(){
	    $email = trim($_POST['email']);
		if(!empty($email)){
		    $user = $this->User->where('email=\''.$email.'\'')->find();
			if($user){
			    echo 1;
			}else{
			    echo 2;
			}
		}else{
		    echo 0;
		}
	}

	public function lostpwd(){
		$this->display('./Tpl/Home/lostpwd.html');
    }

	public function getpwd(){
		if(!chkStr($_POST['username']) || !chkStr($_POST['email'])){
		    $this->error('您输入的信息不完整!');
			exit(0);
		}
		$username = $_POST['username'];
		$email = $_POST['email'];
		$code = strtolower($_POST['code']);
		$checkcode = strtolower($_SESSION['checkcode']);
	
        if($code != $checkcode){
		    $this->error('验证码错误！!');
			exit(0);
		}
		
        $user = $this->User->where('username="'.$username.'" and email="'.$email.'"')->find();
		if(!$user){
			$this->error('该用户不存在！');
			exit(0);
		}
		    
		$mo = new Model();
		$mo->startTrans();

		$hash = md5($user['id'].$user['username'].$user['email'].rand(1111,9999).time());
		$rs = $mo->table('t_user')->where('id='.$user['id'])->setField('hash',$hash);
		
		if($rs){
			$e = $mo->table('t_email')->where('id=2')->find();
			$url = $_SERVER['HTTP_HOST'].$this->path.'/Login/setpw/uid/'.$user['id'].'/hash/'.$hash;
			$e['content'] = str_replace('[url]',$url,$e['content']);
			$issend = $this->sendEmail($user['email'],$e['title'],$e['content']);
		}

		if($rs && $issend){
			$mo->commit();
			$this->assign('jumpUrl',$this->path.'/Login');
			$this->success('请登录注册邮箱继续修改密码！');
		}else{
			$mo->rollback();
			$this->error('提交失败！');
		}
	}

	public function setpw(){
	    if(!chkNum($_GET['uid']) || !chkStr($_GET['hash'])){
		    $this->error('找回失败！');
		}

		$user = $this->User->where('id='.$_GET['uid'].' and hash="'.$_GET['hash'].'"')->find();
		if($user){
			$data['password']=rand(111111,999999);
			$data['password']=md5($data['password']);
			$data['pwdshow']=$data['password'];
            $data['hash'] = '';
		    if($this->User->where('id='.$user['id'])->save($data)){
			    $this->assign('jumpUrl',$this->path.'/Login');
				$this->success('登录密码已经设置为：'.$data['pwdshow'].' 请尽快登录更改密码！');
			}else{
				$this->error('找回失败！');
			}
		}else{
		    $this->error('找回失败！');
		}
	}
}
?>